package com.mashibing.jvm.classLoaderDemo2;

import java.io.*;

public class MyClassLoader extends ClassLoader{

    private String path;

    public MyClassLoader(String path) {
        this.path = path;
    }

    /**
     * 不改变双亲委派：构建ByteArrayOutputStream，再交给defineClass，继而交给loadClass(双亲委派)
     * 感觉写了段无用的代码
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String filePath = name.replace('.', '/');
        String classPath = path + filePath + ".class";

        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(classPath);
            outputStream = new ByteArrayOutputStream();
            int temp = 0;
            while((temp = inputStream.read()) != -1){
                outputStream.write(temp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert outputStream != null;
                outputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        byte[] bytes = outputStream.toByteArray();
        return defineClass(name,bytes,0,bytes.length);
    }

}
